//
//  AFWeatherViewController.m
//  myDemo2
//
//  Created by wuxueying on 14-5-4.
//
//

#import "AFWeatherViewController.h"
#import "AFWeather.h"
#import <CoreLocation/CoreLocation.h>

@interface AFWeatherViewController () <CLLocationManagerDelegate>
{
    CLLocationManager* _manager;
}
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@end
@implementation AFWeatherViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self getLocation];
    [[AFWeather sharedClient]configureClientWithService:AFWeatherAPITest withAPIKey:nil];
}

- (IBAction)getWeather:(id)sender {
    if (_textField.text.length != 0) {
        [[AFWeather sharedClient]fetchForecastOfLocationWithName:_textField.text andCompletionBlock:^(NSDictionary *response, NSError *error) {
            if (!error) {
                NSData *data = [NSJSONSerialization dataWithJSONObject:response options:NSJSONWritingPrettyPrinted error:nil];
                NSLog(@"%@",[NSString stringWithUTF8String:[data bytes]]);
                _textView.text = [NSString stringWithUTF8String:[data bytes]];
            }
        }];
    } else {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"You need to provide a valid name" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)getLocation
{
    CLLocationManager* manager = [[CLLocationManager alloc] init];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyBest;
    manager.distanceFilter = 10;
    [manager startUpdatingLocation];
    _manager = manager ;
}

#pragma - mark 位置定位
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //我们只查询一次
    [manager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation: newLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array objectAtIndex:0];
             NSString *provinceStr = [placemark.administrativeArea substringToIndex:placemark.administrativeArea.length - 1];
             NSString *cityStr = [placemark.locality substringToIndex:placemark.locality.length - 1];
             _textField.text = cityStr;
         }
     }];
}

@end
